package com.wiretap.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.wiretap.dao.UserDao;
import com.wiretap.po.User;
import com.wiretap.util.Pager;

public class UserDaoImpl implements UserDao {

	private SessionFactory sessionFactory;

	@Override
	public void addUser(User user) throws Exception {
		try {
			this.sessionFactory.getCurrentSession().persist(user);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("增加用户时时发生异常");
		}
	}

	@Override
	public int updateUser(User user) throws Exception {
		try {
			sessionFactory.getCurrentSession().update(user);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("updateUser发生异常");
		}
		return 1;
	}

	@SuppressWarnings("unchecked")
	@Override
	public User getUserByPhone(String phone) throws Exception {
		try {
			List<User> users = sessionFactory.getCurrentSession().createQuery("from User a where a.phone=:phone").setString("phone", phone).list();
			if (users != null && !users.isEmpty()) {
				return users.get(0);
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("getUserByPhone发生异常");
		}
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pager<User> getAllUser(int currentPage, int pageSize) throws Exception {
		try {
			Session sesion = this.sessionFactory.getCurrentSession();
			int totalCount = sesion.createQuery("from User u where u.visible=:visible").setBoolean("visible", true).list().size();
			int pageCount = (totalCount % pageSize == 0) ? totalCount / pageSize : (totalCount / pageSize) + 1;
			List<User> list = sesion.createQuery("from User u where u.visible=:visible order by u.id desc").setBoolean("visible", true).setFirstResult((currentPage - 1) * pageSize)
					.setMaxResults(pageSize).list();
			Pager<User> pager = new Pager<User>(list, currentPage, totalCount, pageCount);
			return pager;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("getAllUser发生异常");
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pager<User> searchUserByPhone(String phone, int currentPage, int pageSize) throws Exception {
		try {
			Session sesion = this.sessionFactory.getCurrentSession();
			int totalCount = sesion.createQuery("from User a where a.visible=:visible and a.phone like :phone").setBoolean("visible", true).setString("phone", "%" + phone + "%").list().size();
			int pageCount = (totalCount % pageSize == 0) ? totalCount / pageSize : (totalCount / pageSize) + 1;
			List<User> list = sesion.createQuery("from Usera where a.visible=:visible and a.phone like :phone order by u.id desc").setBoolean("visible", true).setString("phone", "%" + phone + "%")
					.setFirstResult((currentPage - 1) * pageSize).setMaxResults(pageSize).list();
			Pager<User> pager = new Pager<User>(list, currentPage, totalCount, pageCount);
			return pager;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("searchUserByPhone发生异常");
		}
	}

	@Override
	public int removeUser(String[] ids) throws Exception {
		try {
			String hql = "delete from User a where ";
			for (int i = 0; i < ids.length; i++) {
				hql += "a.id=?";
				if (i != ids.length - 1) {
					hql += " or ";
				}
			}
			Query query = sessionFactory.getCurrentSession().createQuery(hql);
			for (int i = 0; i < ids.length; i++) {
				query.setString(i, ids[i]);
			}
			return query.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("removeUser发生异常");
		}
	}

	@Override
	public User getUserById(String id) throws Exception {
		try {
			Long _id = Long.parseLong(id);
			return (User) sessionFactory.getCurrentSession().get(User.class, _id);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("getUserById发生异常");
		}
	}

	@Override
	public long getUserCount() throws Exception {
		try {
			Query query = sessionFactory.getCurrentSession().createQuery("select count(*) from User a where a.visible=:visible").setBoolean("visible", true);
			return ((Number) query.uniqueResult()).longValue();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("getUserCount发生异常");
		}
	}

	@Override
	public int setUserVisibility(String[] ids, boolean visibility) throws Exception {
		try {
			String hql = "update User a set a.visible=? where ";
			for (int i = 0; i < ids.length; i++) {
				hql += "a.id=?";
				if (i != ids.length - 1) {
					hql += " or ";
				}
			}
			Query query = sessionFactory.getCurrentSession().createQuery(hql);
			query.setBoolean(0, visibility);
			for (int i = 0; i < ids.length; i++) {
				query.setString(i + 1, ids[i]);
			}
			return query.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("setUserVisibility发生异常");
		}
	}
}
